<?php
/**
* @author moufer<moufer@163.com>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'howcan');

$catid = isset($_GET['catid']) ? (int)$_GET['catid'] : (int)$MOD['pid'];
!$catid and redirect('item_empty_default_pid');

//实例化主题类
$I =& $_G['loader']->model('item:subject');
$I->get_category($catid);
if(!$pid = $I->category['catid']) {
    redirect('item_cat_empty');
}


//载入配置信息
$catcfg =& $I->category['config'];
$modelid = $I->category['modelid'];
$rogid = $I->category['review_opt_gid'];

//载入模型
$model = $I->variable('model_' . $modelid);
//载入点评选项
$reviewpot = $_G['loader']->variable('opt_' . $rogid, 'review');

//分类分级变量1主2子
$category = $_G['loader']->variable('category_' . $pid, 'item');
//判断子分类是否禁用
if(!$category[$catid]['enabled']) redirect('item_cat_disabled');
//当前catid的级别
$category_level = $category[$catid]['level'];
$urlpath = array();
$urlpath[] = url_path($category[$pid]['name'], url("item/list/catid/$pid"));
if($catid != $pid) {
    if($category_level > 2) {
        $urlpath[] = url_path($category[$category[$catid]['pid']]['name'], url("item/list/catid/{$category[$catid]['pid']}"));
    }
    $urlpath[] = url_path($category[$catid]['name'], url("item/list/catid/$catid"));
}
$subcats = null;
if($category_level<=2) {
	foreach($category as $__v) {
		if($__v['pid']==$catid) {
			$subcats[] = $__v['catid'];
		}
	}
	unset($__v);
}

//兼容以前的版本
$pcat =& $category;
$where = array();
//使用了地图功能
if($model['usearea']) {

	$aid = (int) $_GET['aid'];

	//载入地区
	$area = $_G['loader']->variable('area_1');
    //地区级别
    $area_level = $area[$aid]['level'];

    if($area_level == 2) {
        $paid = 0;
    } else {
        $paid = $area[$aid]['pid'];
    }

    if($paid) {
        $urlpath[] = url_path($area[$paid]['name'], url("item/list/catid/$pid/aid/$paid"));
    }
    if($paid != $aid) {
        $urlpath[] = url_path($area[$aid]['name'], url("item/list/catid/$pid/aid/$aid"));
    }

	$boroughs = $streets = '';
	foreach($area as $key => $val) {
		if($val['level'] == 2) $boroughs[$key] = $val['name'];
		if($val['level'] == 3 && ($aid==$val['pid']||$paid==$val['pid'])) $streets[$key] = $val['name'];
	}
}
//属性组处理
$atts = array(); 
if($att = _get('att',null,'_T')) {
    $attp = $att;
    $att = explode('_', $att);
    foreach($att as $att_v) {
        list($att_catid, $att_id) = explode('.', $att_v);
        if(!$att_catid || !$att_id) continue;
        $atts[$att_catid] = $att_id;
    }
}
$atturl = item_att_url();

if($aid) $where['aid'] = (int) $aid;
if($catid != $pid) {
    $where['catid'] = array_merge((array)$catid, $I->get_sub_catids($catid));
} else {
    $where['pid'] = (int) $pid;
}
$where['status'] = 1;

$mylat=$_GET['lat']/1e6;
$mylng=$_GET['lng']/1e6;
$nearto = 0.5;

$where['map_lat'] = array('where_between_and',array($mylat - $nearto,$mylat + $nearto));
// ,'where_less',array($mylat + $nearto)); 
$where['map_lng'] = array('where_between_and',array($mylng - $nearto,$mylng + $nearto)); 


// 显示数量
$numlist = array (10, 20, 40);
// 显示方式
$typelist = lang('item_list_displytype');
$type = _cookie('list_display_item_subject_type', $catcfg['displaytype'], '_T');
$type = isset($typelist[$type]) ? $type : 'normal';
// 排序数组
$orderlist = lang('item_list_orderlist');

//查询的数组
$order_arr  = array(
    'finer' => array('finer'=>'DESC'),
    'avgsort' => array('avgsort'=>'DESC'),
    'reviews' => array('reviews'=>'DESC'),
    'enjoy' => array('best'=>'DESC'),
    'price' => array('avgprice'=>'DESC'),
    'price_s' => array('avgprice'=>'ASC'),
    'picture' => array('pictures'=>'DESC'),
    'picture_s' => array('pictures'=>'ASC'),
    'addtime' => array('addtime'=>'DESC'),
    'pageviews' => array('pageviews'=>'DESC'),
);

if($catcfg['useprice']) {
    $orderlist['price'] = $catcfg['useprice_title'];
}

$orderby = _cookie('list_display_item_subject_orderby',$catcfg['listorder'],'_T');
if(!$orderby || !isset($order_arr[$orderby])) {
	$orderby = $catcfg['listorder'];
}

$fields = $I->variable('field_' . $modelid);

$select = 's.sid,pid,catid,domain,name,subname,avgsort,sort1,sort2,sort3,sort4,sort5,sort6,sort7,sort8,best,finer,pageviews,reviews,pictures,favorites,thumb,video,description';
if($model['usearea']) {
    if(false == strpos($select, 'aid')) $select .= ',aid';
    if(false == strpos($select, 'map_lat')) $select .= ',map_lat';
    if(false == strpos($select, 'map_lng')) $select .= ',map_lng';
}
if($catcfg['useprice']) {
    if(false == strpos($select, 'avgprice')) $select .= ',avgprice';
}
$select_arr = explode(',', $select);
$custom_field = array();
foreach($fields as $val) {
    if(!$val['show_list']) continue;
	$ver_field = array('mappoint');
    if(!in_array($val['fieldname'], $select_arr) && !in_array($val['fieldname'], $ver_field)) {
        $select .= ',' . $val['fieldname'];
    }
    if(!in_array($val['fieldname'], array('name','subname','mappoint','owner','status','templateid','listorder'))) {
        $custom_field[] = $val;
    }
}
unset($select_arr, $val);

$num = abs(_cookie('list_display_item_subject_num', (int)$MOD['list_num'], 'intval'));
(!$num || !in_array($num, $numlist)) && $num = 20;
$start = get_start($_GET['page'], $num);
if($total = _get('total',null,MF_INT)) {
	list(, $list) = $I->find($select, $where, $order_arr[$orderby], $start, $num, false, $pid, $atts);
} else {
	list($total, $list) = $I->find($select, $where, $order_arr[$orderby], $start, $num, TRUE, $pid, $atts);
}

if($total) {
    $multipage = multi($total, $num, $_GET['page'], url("item/list/catid/$catid/aid/$aid/order/$order/type/$type/att/$atturl/num/$num/total/$total/page/_PAGE_"));
}

if($total) {
    //内容
//    $FD =& $_G['loader']->model(MOD_FLAG.':fielddetail');
    //样式设计
    $FD->td_num = 1; //表只有1个td
    $FD->class = "";
    $FD->width = "";
    $FD->align = "left";
}

define('SUBJECT_CATID', $catid);

$active = array();
$active['type'][$type] = ' class="selected"';
$active['num'][$num] = ' class="selected"';
$active['orderby'][$orderby] = ' class="selected"';

// 最近的浏览COOKIE
$cookie_subjects = $I->read_cookie($pid);

$_HEAD['keywords'] = $catcfg['meta_keywords'];
$_HEAD['description'] = $catcfg['meta_description'];

// echo $model['tplname_list']; exit;
//include template($model['tplname_list']);
//include template('item_subject_list_normal');

$shoplists = array();
// $category = $_G['loader']->variable('category_'.$I->category['catid'], 'item');
$area = $_G['loader']->variable('area_1');

while($val = $list->fetch_array()) {
	$val['distance'] = CaculateDistance($val['map_lat'],$val['map_lng'],$mylat,$mylng);
//    $val['categoryname'] = $category[$category[$val['catid']]['pid']]['name'] .' '. $category[$val[catid]]['name'];	
	$val['categoryname'] = $category[$val[catid]]['name'];	
    $val['categoryname'] .= ' '.$area[$val['aid']]['name'].' '.$val['video'];
	$shoplists[] = $val;
}

// http://maps.google.com/maps/api/geocode/json?latlng=29.87863,121.56069&sensor=true_or_false

$shoplists = sysSortArray($shoplists,"distance","SORT_ASC");

errMessage(0,json_encode($shoplists));

// print_r(getPoint("東京都港区"));

exit;

function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
{
    if(!is_array($ArrayData))
    {
        return $ArrayData;
    }
 
    // Get args number.
    $ArgCount = func_num_args();
 
    // Get keys to sort by and put them to SortRule array.
    for($I = 1;$I < $ArgCount;$I ++)
    {
        $Arg = func_get_arg($I);
        if(!eregi("SORT",$Arg))
        {
            $KeyNameList[] = $Arg;
            $SortRule[]    = '$'.$Arg;
        }
        else
        {
            $SortRule[]    = $Arg;
        }
    }
 
    // Get the values according to the keys and put them to array.
    foreach($ArrayData AS $Key => $Info)
    {
        foreach($KeyNameList AS $KeyName)
        {
            ${$KeyName}[$Key] = $Info[$KeyName];
        }
    }
 
    // Create the eval string and eval it.
    $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
    eval ($EvalString);
    return $ArrayData;
}

function item_att_url($catid=null, $attid=null, $del=false) {
    global $atts;
    $myatts = $atts;
    if($catid) {
        if($del) {
            unset($myatts[$catid]);
        } else {
            $myatts[$catid] = $attid;
        }
    }
    $url = $split = '';
    foreach($myatts as $catid=>$attid) {
        $url .= $split . $catid .'.'.$attid;
        $split = '_';
    }
    return $url;
}

function rad($radius){
    $radius = $radius * M_PI / 180.0;
    return $radius;
}

function CaculateDistance($lat1,$lng1,$lat2,$lng2){
    $EARTH_RADIUS = 6378.137;
    $radLat1 = rad($lat1);
    $radLng1 = rad($lng1);
    $radLat2 = rad($lat2);
    $radLng2 = rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $temp = 2 * Asin(Sqrt(Pow(Sin($a / 2), 2) + Cos($radLat1) * Cos($radLat2) * Pow(Sin($b / 2), 2))) * $EARTH_RADIUS;
    //$temp =acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$EARTH_RADIUS;
//    $temp =Round($temp * 10000) / 10000;
    $temp =Round($temp * 100) * 10;    // 10米为最小单位
    return $temp;
}

function xml2array($url, $get_attributes = 1, $priority = 'tag')
{
    $contents = "";
    if (!function_exists('xml_parser_create')){
        return array ();
    }
    $parser = xml_parser_create('');
    if (!($fp = @ fopen($url, 'rb'))){
        return array ();
    }
    while (!feof($fp)){
        $contents .= fread($fp, 8192);
    }
    fclose($fp);
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);
    if (!$xml_values){
        return "none";
    }
    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();
    $current = & $xml_array;
    $repeated_tag_index = array();
    foreach ($xml_values as $data){
        unset($attributes, $value);
        extract($data);
        $result = array ();
        $attributes_data = array ();
        if (isset ($value)){
            if ($priority == 'tag'){
                $result = $value;
            }else{
                $result['value'] = $value;
            }
        }
        if (isset ($attributes) and $get_attributes){
            foreach ($attributes as $attr => $val){
                if ($priority == 'tag'){
                    $attributes_data[$attr] = $val;
                }else{
                    $result['attr'][$attr] = $val;
                }
            }
        }
        if ($type == "open"){
            $parent[$level -1] = & $current;
            if (!is_array($current) or (!in_array($tag, array_keys($current)))){
                $current[$tag] = $result;
                if ($attributes_data){
                    $current[$tag . '_attr'] = $attributes_data;
                }
                $repeated_tag_index[$tag . '_' . $level] = 1;
                $current = & $current[$tag];
            }else{
                if (isset ($current[$tag][0])){
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    $repeated_tag_index[$tag . '_' . $level]++;
                }else{
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 2;
                    if (isset ($current[$tag . '_attr'])){
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                        unset ($current[$tag . '_attr']);
                    }
                }
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                $current = & $current[$tag][$last_item_index];
            }
        }elseif ($type == "complete"){
            if (!isset ($current[$tag])){
                $current[$tag] = $result;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                if ($priority == 'tag' and $attributes_data){
                    $current[$tag . '_attr'] = $attributes_data;
                }
            }else{
                if (isset ($current[$tag][0]) and is_array($current[$tag])){
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    if ($priority == 'tag' and $get_attributes and $attributes_data){
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag . '_' . $level]++;
                }else{
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $get_attributes){
                        if (isset ($current[$tag . '_attr'])){
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                        if ($attributes_data){
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
            }
        }elseif ($type == 'close'){
            $current = & $parent[$level -1];
        }
    }
    return ($xml_array);
}

function getPoint($address){
    $find = array("\n","\r"," ");
    $replace = array("","","+");
    $address = str_replace( $find,$replace, $address);
    $url = "http://www.geocoding.jp/api/?v=1.1&q=".$address;    
    $response = xml2array($url);
    $lat = $response['result']['coordinate']["lat"];
    $lng = $response['result']['coordinate']['lng'];
    if (!empty($lat)) {
        $response = array('lat'=>$lat,'lng'=>$lng);
        return  $response;
    }else{
        return array();
    }
}





?>

<!--{if $total}-->
<!--{eval $index=0;}-->
<!--{dbres $list $val}-->
    <div class="itemlist{if $val[finer]} itemfiner{/if}">
        <div class="pic">
            <div id="item_pic_$val[sid]"><a href="{url item/detail/id/$val[sid]}"><img{if $val[thumb]} onmouseover="tip_start(this);" {/if} src="{URLROOT}/{if $val[thumb]}$val[thumb]{else}static/images/noimg.gif{/if}" /></a><b></b></div>
        </div>
        <div class="item">
            <div class="info">
                <div>
                    <h3 id="item_name_$val[sid]"><a href="{url item/detail/id/$val[sid]}">$val[name]&nbsp;$val[subname]</a></h3>
                </div>
                <table class="custom_field_list" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td>
                            <!--{loop $reviewpot $_val}-->$_val[name]:<span class="font_2" style="font-size:16px;">{print cfloat($val[$_val[flag]])}</span><!--{/loop}-->&nbsp;综合得分:<span class="font_1" style="font-size:16px;"><strong>{print cfloat($val[avgsort])}</strong></span>
                        </td>
                    </tr>
                    <!--{loop $custom_field $_val}-->
                        <!--{print $FD->detail($_val, $val[$_val['fieldname']], $val[sid])."\r\n"}-->
                    <!--{/loop}-->
                </table>
            </div>
            <div class="stat">
                <!--{eval $reviewcfg = $_G['loader']->variable('config','review');}-->
                <li class="start{print get_star($val[avgsort],$reviewcfg[scoretype]);}"></li>
                <!--{if $catcfg[useprice]}-->
                <li><span class="font_2">$val[avgprice]</span> $catcfg[useprice_unit]</li>
                <!--{/if}-->
                <li><a href="{url item/detail/id/$val[sid]}#review"><span class="font_2">$val[reviews]</span> 条点评</a></li>
                <li><a href="{url item/pic/sid/$val[sid]}"><span class="font_2">$val[pictures]</span> 张图</a></li>
            </div>
        </div>
        <div class="clear"></div>
    </div>
	<!--{if ++$index==2}-->
	<div id="adv_1"></div>
	<!--{/if}-->
<!--{/dbres}-->
<!--{else}-->
    <div class="messageborder">
        <span class="msg-ico">本板块暂时没有主题信息，<a href="{url item/member/ac/subject_add/pid/$pid}">我要添加</a>。</span>
    </div>
<!--{/if}-->































?>